import React, { JSX, ReactNode, useState } from 'react';
import { Text, TouchableOpacity, View, ViewProps } from 'react-native';

interface TabPanelProps {
  children: ReactNode;
  title: string;
  name: string;
}

type TrapezoidTabProps = {
  children:
    | React.ReactElement<TabPanelProps>
    | React.ReactElement<TabPanelProps>[];
  onTabChange?: (key: string) => void;
} & ViewProps

// TabPanel组件 - 用于包装每个Tab的内容
const TrapezoidTabPanel: React.FC<TabPanelProps> = ({ children }) => {
  return <>{children}</>;
};

// 主TrapezoidTab组件
const TrapezoidTab: React.FC<TrapezoidTabProps> = ({
  children,
  onTabChange,
  ...props
}) => {
  const tabPanels = React.Children.toArray(
    children
  ) as React.ReactElement<TabPanelProps>[];
  console.log(`渲染：内容是：${tabPanels[0].key}`)
  const [activeTab, setActiveTab] = useState<string>(
    () => tabPanels[0].props.name ?? ''
  );

  const handleTabPress = (key: string): void => {
    setActiveTab(key);
    if (onTabChange) {
      onTabChange(key);
    }
  };

  // 找到当前选中的Tab内容
  const activeTabContent = tabPanels.find(
    (panel) => panel.props.name === activeTab
  );

  const renderTabHeader = (): JSX.Element => (
    <View className="flex-row bg-[#ECF8F3]">
      {tabPanels.map((panel) => {
        const key = panel.props.name;
        const title = panel.props.title || key || 'Tab';
        const isActive = key === activeTab;

        return (
          <TouchableOpacity
            key={key + 'button'}
            className={`flex-1 h-11 items-center justify-center gap-[2px] ${
              isActive ? 'bg-white' : ''
            }`}
            onPress={() => handleTabPress(key)}
          >
            <Text
              className={`text-[15px] font-medium ${
                isActive ? 'text-brand1' : 'text-text2'
              }`}
            >
              {title}
            </Text>
            {/* 指示条 */}
            {isActive && (
              <View className="bg-brand1 h-1 w-4 rounded-sm" />
            )}
          </TouchableOpacity>
        );
      })}
    </View>
  );

  const renderTabContent = (): JSX.Element => (
    <View className="flex-1 bg-white p-5">
      {activeTabContent ? activeTabContent.props.children : null}
    </View>
  );

  return (
    <View className="bg-fill4" {...props}>
      {renderTabHeader()}
      {renderTabContent()}
    </View>
  );
};

export default React.memo(TrapezoidTab);
export { TrapezoidTabPanel };
